<template>
  <div class="container">
    <Menu></Menu>
    <div class="box">
      <t-menu theme="light" default-value="1" style="margin-right: 8px; height: auto" @change="changeHandler">
        <template #logo> <NotificationIcon />消息中心~ </template>
        <t-menu-item value="1"> 聊天广场 </t-menu-item>
        <t-menu-item value="2"> 我的消息 </t-menu-item>
      </t-menu>
      <div class="box-right">
        <div class="box-right-top">
          <div>{{ currentMenu }}</div>
        </div>
        <div class="box-right-main">
          <div v-if="currentMenu == '聊天广场'" class="box-right-main-sider">
            <div v-for="member in members" :key="member.leiId" class="box-right-main-sider-item">
              <img v-if="member.avatar" class="box-right-main-sider-item-avatar" :src="member.avatar" alt="" />
              <img v-else class="box-right-main-sider-item-avatar" src="../../assets/datou.jpg" alt="" />
              <div class="box-right-main-sider-item-right">
                <div class="box-right-main-sider-item-right-name">{{ member.nickname }}</div>
                <div class="box-right-main-sider-item-right-des">{{ member.introduction }}</div>
              </div>
            </div>
          </div>
          <div v-else class="box-right-main-sider">
            <div
              v-for="communication in communications"
              :key="communication.leiId"
              class="box-right-main-sider-item"
              @click="clickCommunication(communication)"
            >
              <img
                v-if="communication.avatar"
                class="box-right-main-sider-item-avatar"
                :src="communication.avatar"
                alt=""
              />
              <img v-else class="box-right-main-sider-item-avatar" src="../../assets/datou.jpg" alt="" />
              <div class="box-right-main-sider-item-right">
                <div class="box-right-main-sider-item-right-name">{{ communication.nickname }}</div>
                <div class="box-right-main-sider-item-right-des">{{ communication.introduction }}</div>
              </div>
            </div>
          </div>
          <div class="box-right-main-content">
            <div ref="chat" class="box-right-main-content-chat">
              <div v-for="(message, index) in messageList" :key="index">
                <div v-show="message.createdBy != loginId" class="box-right-main-content-chat-item">
                  <img
                    v-if="message.avatar"
                    class="box-right-main-content-chat-item-avatar"
                    :src="message.avatar"
                    alt=""
                  />
                  <img v-else class="box-right-main-content-chat-item-avatar" src="../../assets/datou.jpg" alt="" />
                  <div class="box-right-main-content-chat-item-right">
                    <div class="box-right-main-content-chat-item-name">
                      {{ message.nickName }} &nbsp; {{ dayjs(message.createdTime).format('HH:mm') }}
                    </div>
                    <div class="box-right-main-content-chat-item-text">{{ message.messageContent }}</div>
                  </div>
                </div>
                <div
                  v-show="message.createdBy == loginId"
                  style="justify-content: end"
                  class="box-right-main-content-chat-item"
                >
                  <div class="box-right-main-content-chat-item-right">
                    <div style="text-align: end" class="box-right-main-content-chat-item-name">
                      {{ dayjs(message.createdTime).format('HH:mm') }} &nbsp; {{ message.nickName }}
                    </div>
                    <div
                      style="background-color: aquamarine; border-radius: 10px 0 10px 10px"
                      class="box-right-main-content-chat-item-text"
                    >
                      {{ message.messageContent }}
                    </div>
                  </div>
                  <img
                    v-if="message.avatar"
                    style="margin-left: 8px; margin-right: 0"
                    class="box-right-main-content-chat-item-avatar"
                    :src="message.avatar"
                    alt=""
                  />
                  <img
                    v-else
                    style="margin-left: 8px; margin-right: 0"
                    class="box-right-main-content-chat-item-avatar"
                    src="../../assets/datou.jpg"
                    alt=""
                  />
                </div>
              </div>
            </div>
            <t-textarea
              v-model="addMessageDTO.messageContent"
              class="box-right-main-content-input"
              placeholder="我是无敌小天才我是无敌小天才我是无敌小天才我是无敌小天才"
              name="description"
            />
            <div class="btns">
              <t-button @click="sendMessage">发送</t-button>
              <t-button theme="default" variant="base" @click="addMessageDTO.messageContent = ''">重置</t-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { NotificationIcon } from 'tdesign-icons-vue-next';
import { MenuProps } from 'tdesign-vue-next';
import { onBeforeUnmount, onMounted, onUpdated, ref } from 'vue';
import { useRoute } from 'vue-router';

import { addMessageApi, queryDetailMessageApi, queryMessageApi } from '@/api/message';
import { getUserByIdApi, getUserFollowApi } from '@/api/user';
import Menu from '@/components/Menu.vue';

const route = useRoute();
// 获取页面元素
const chat = ref(null);
// 当前登录用户id
const loginId = route.params.id;
// 消息列表
const messageList = ref([]);
// 在线人数列表
const members = ref([]);
// 与我对话的人数列表
const communications = ref([]);
// 在线人数id列表
const idList = ref([]);
// 条件分页查询所有消息传参
const queryMessageDTO = ref({
  messageContent: '',
  createdBy: '',
  current: 1,
  pageSize: 100,
});
// 发送消息传参
const addMessageDTO = ref({
  messageContent: '',
  createdBy: localStorage.getItem('id'),
  receiveId: '',
});
// 分页条件查询私信传参
const queryDetailMessageDTO = ref({
  receiveId: '',
  createdBy: localStorage.getItem('id'),
});
// 当前菜单项
const currentMenu = ref('聊天广场');
let socket;

onMounted(() => {
  // 创建 WebSocket 连接
  socket = new WebSocket(`ws://localhost:8085/lei/socket?erp=${loginId}`);

  // 监听连接打开事件
  socket.onopen = () => {
    setInterval(() => {
      socket.send('ྀི');
    }, 1500);
  };

  // 监听消息事件
  socket.onmessage = async (event) => {
    if (currentMenu.value === '聊天广场') {
      const res = event.data.split('ྀི');
      if (!idList.value.includes(res[0])) {
        idList.value.push(res[0]);
        await getUserById(res[0]);
      }
    }
    if (currentMenu.value === '我的消息') {
      await queryDetailMessage();
    }
  };

  // 监听错误事件
  socket.onerror = (error) => {
    console.error('WebSocket error:', error);
  };

  // 监听连接关闭事件
  socket.onclose = () => {
    console.log('WebSocket connection closed');
  };

  scrollToBottom();
});

onUpdated(() => {
  scrollToBottom();
});

onBeforeUnmount(() => {
  // 在组件卸载前关闭 WebSocket 连接
  if (socket) {
    socket.close();
  }
});

const changeHandler: MenuProps['onChange'] = (active) => {
  switch (active) {
    case '1':
      members.value.length = 0;
      currentMenu.value = '聊天广场';
      queryMessage();
      break;
    case '2':
      currentMenu.value = '我的消息';
      messageList.value.length = 0;
      getUserFollow();
      break;
    default:
      break;
  }
};

// 发送聊天内容
const sendMessage = async () => {
  addMessageDTO.value.createdBy = loginId as string;
  socket.send(addMessageDTO.value);
  await addMessageApi(addMessageDTO.value);
  addMessageDTO.value.messageContent = '';
  queryMessage();
};

// 滚动到对话框底部
const scrollToBottom = () => {
  chat.value.scrollTop = chat.value.scrollHeight;
};

// 根据用户id查询用户信息
const getUserById = async (userId) => {
  const res = await getUserByIdApi(userId);
  if (currentMenu.value === '聊天广场') {
    members.value.push(res.data);
  }
};

// 查询用户关注的所有用户
const getUserFollow = async () => {
  const res = await getUserFollowApi(loginId);
  communications.value = res.data;
};

// 条件分页查询消息列表
const queryMessage = async () => {
  const res = await queryMessageApi(queryMessageDTO.value);
  messageList.value = res.data;
};
queryMessage();

// 点击我的消息菜单项
const clickCommunication = (communication) => {
  addMessageDTO.value.receiveId = communication.leiId;
  queryDetailMessageDTO.value.receiveId = communication.leiId;
  queryDetailMessageDTO.value.createdBy = loginId as string;
  queryDetailMessage();
};

// 查询私信消息
const queryDetailMessage = async () => {
  const res = await queryDetailMessageApi(queryDetailMessageDTO.value);
  console.log(res.data);
  messageList.value = res.data;
};
</script>

<style scoped>
@import './index.less';
</style>
